package cn.jhc;


import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ProtocolVersion;
import org.apache.http.RequestLine;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.FileEntity;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler;

public class RootHandler implements HttpRequestHandler{

    @Override
    public void handle(HttpRequest request, HttpResponse response, HttpContext context)
            throws HttpException, IOException {
        // String entityStr = "<html><body><h2>你好web！</h2></body></html>";
        // StringEntity strEntity = new StringEntity(entityStr, ContentType.create("text/html", "utf-8"));
        // response.setEntity(strEntity);
        // String dirname = "/mnt/d/zhqworks/html5/index.html" ;
        // File file1 = new File(dirname);
        // FileEntity test1 = new FileEntity(file1, ContentType.create("html", "utf-8"));
        // response.setEntity(test1);
        RequestLine requestLine = request.getRequestLine();
        String uri = requestLine.getUri();
        String filename = uri.substring(uri.lastIndexOf("/"));
        System.out.println(filename);
        InputStream in = getClass().getResourceAsStream(filename);
        if (in != null) {
            InputStreamEntity entity = new InputStreamEntity(in);
            response.setEntity(entity);
        }else {
            response.setStatusLine(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_NOT_FOUND);
        }

    }
    
}
